// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
const got = require('got')
const fs = require('fs')
const request = require("request")

cloud.init()

// cloud.init({
//   env: 'xcx-release-05c56c'
// })

// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  const app = new TcbRouter({
    event
  });

  // app.use 表示该中间件会适用于所有的路由
  app.use(async(ctx, next) => {
    ctx.data = {};
    ctx.data.title = '爱貌貌===网络请求函数';
    ctx.data.openid = wxContext.OPENID;
    ctx.data.appid = wxContext.APPID;
    ctx.data.unionid = wxContext.UNIONID;
    await next(); // 执行下一中间件
  });

  // 路由为数组表示，该中间件适用于 get 和 get 两个路由
  app.router(['get', 'post'], async(ctx, next) => {
    await next(); //执行下一中间件
  });

  // GET 路由为字符串，该中间件只适用于 get 路由
  app.router('get', async(ctx, next) => {
    ctx.data.name = '发送get请求';
    ctx.data.url = event.url; //请求的URL
    try {
      const response = await got(ctx.data.url);
      ctx.body = {
        code: 'ok',
        msg: ctx.data,
        data: response.body
      };
      console.log(response.body);
    } catch (error) {
      console.log(error.response.body);
    }
    await next();
  });

  // POST 路由为字符串，该中间件只适用于 post 路由
  app.router('post', async(ctx, next) => {
    ctx.data.name = '发送post请求';
    ctx.data.url = event.url; //请求的URL
    try {
      const response = await got(ctx.data.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: '测试POST请求的数据',
          value: 3423
        })
      });
      ctx.body = {
        code: 'ok',
        msg: ctx.data,
        data: response.body
      };
      console.log(response.body);
    } catch (error) {
      console.log(error.response.body);
    }
    await next();
  });

  //post 请求一张图片
  app.router('postImg', async (ctx, next) => {
    ctx.data.name = '发送post请求获得一张图片';
    ctx.data.url = event.url; //请求的URL
    try {
      var upload = await cloud.uploadFile({
        cloudPath: 'demo111.jpg',
        fileContent: request(event.url),
      })

      ctx.body = {
        code: 'ok',
        msg: ctx.data,
        imgSrc: upload
      };

    } catch (error) {
      console.log(error);
    }
    await next();
  });


  return app.serve();
}